// Bristleback plugin - Copyright (c) 2010 bristleback.googlecode.com
// ---------------------------------------------------------------------------
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
// This library is distributed in the hope that it will be useful,
// but without any warranty; without even the implied warranty of merchantability
// or fitness for a particular purpose.
// You should have received a copy of the GNU Lesser General Public License along
// with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
// ---------------------------------------------------------------------------
package pl.bristleback.server.bristle;

import pl.bristleback.server.bristle.config.BristleConstants;
import pl.bristleback.server.bristle.integration.spring.SpringIntegrationUtil;
import org.apache.log4j.Logger;
import org.jwebsocket.factory.JWebSocketFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Simple servlet context listener for websocket web applications using Jwebsocket and Bristleback plugin.
 * Custom context parameters can be used to enable Spring integration or specify path to jwebsocket.xml configuration file. 
 * <p/>
 * Created on: 2010-10-14 15:36:52 <br/>
 *
 * @author Wojciech Niemiec
 */
public class BristlebackWebContextListener implements ServletContextListener {
  private static Logger log = Logger.getLogger(BristlebackWebContextListener.class.getName());

  @Override
  public void contextInitialized(ServletContextEvent sce) {
    String configFilename = sce.getServletContext().getInitParameter(BristleConstants.CONFIG_FILE_LOCATION_CONTEXT_VARIABLE_NAME);
    String enableSpring = sce.getServletContext().getInitParameter(BristleConstants.SPRING_INTEGRATION_CONTEXT_VARIABLE_NAME);

    enableSpringIntegration(enableSpring, sce);

    startJWebsocket(configFilename);
  }

  private void enableSpringIntegration(String enableSpringParameter, ServletContextEvent servletContextEvent) {
    boolean enableSpring = false;
    if (enableSpringParameter != null) {
      enableSpring = Boolean.parseBoolean(enableSpringParameter);
    }
    if (enableSpring) {
      SpringIntegrationUtil.setApplicationContextFromServlet(servletContextEvent.getServletContext());
    }
  }

  private void startJWebsocket(String configFilename) {
    JWebSocketFactory.start(configFilename);
  }

  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    JWebSocketFactory.stop();
  }
}
